package com.onlyxiahui.extend.spring.webmvc.dispatcher.config;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.onlyxiahui.common.dispatcher.ServiceMessageHandler;
import com.onlyxiahui.common.dispatcher.constant.ActionConstant;
import com.onlyxiahui.common.dispatcher.handler.ResultDataHandler;
import com.onlyxiahui.common.dispatcher.util.DispatcherJsonUtil;
import com.onlyxiahui.extend.spring.webmvc.dispatcher.properties.OnlyActionDispatcherProperties;
import com.onlyxiahui.framework.action.dispatcher.extend.ActionResponse;
import com.onlyxiahui.framework.action.dispatcher.extend.ArgumentBox;

/**
 * 
 * 
 * <br>
 * Date 2019-12-03 17:32:01<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
@RestController
public class ActionPortal {

	private ResultDataHandler rh = new ResultDataHandler();

	@Resource
	private ServiceMessageHandler handler;

	@Autowired()
	private OnlyActionDispatcherProperties onlyActionDispatcherProperties;

	@ResponseBody
	public Object message(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) {
		String path = request.getRequestURI();

		ArgumentBox argumentBox = handler.getArgumentBox();
		argumentBox.put(ActionConstant.REQUEST_PATH, path);
		argumentBox.put(HttpServletRequest.class, request);
		argumentBox.put(HttpServletResponse.class, response);

		request.setAttribute(ActionConstant.ARGUMENT_BOX, argumentBox);
		request.setAttribute(ActionConstant.REQUEST_BODY_CACHE, body);

		ActionResponse actionResponse = new ActionResponse() {

			@Override
			public void write(Object data) {
				put(response, argumentBox, body, data);
			}
		};
		return handler.onMessage(body, path, actionResponse, argumentBox);
	}

	private void put(HttpServletResponse response, ArgumentBox argumentBox, String body, Object data) {
		if (onlyActionDispatcherProperties.isResponseHandleEnable()) {
			data = rh.result(data, body, argumentBox);
		}
		String json = DispatcherJsonUtil.toJson(data);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		writer(response, json);
	}

	public void writer(HttpServletResponse response, String text) {
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.println(text);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != writer) {
				writer.close();
			}
		}
	}
}
